import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Scanner;


public class Query 
{

	/**
	 * @param args
	 * @throws Exception 
	 */
	public static void main(String[] args) throws Exception 
	{
		System.out.println(String.format("Peticion %1$tH:%1$tM:%1$tS:%1$tL", java.util.Calendar.getInstance()));
		try 
		{
	    	Scanner entradaUser = new Scanner(System.in);
	   	 	System.out.print("User ID: ");
	   	 	String login = entradaUser.next();
	    	
	    	Scanner entradaPassword = new Scanner(System.in);
	    	System.out.print("Password: ");
	    	String password = entradaPassword.next();

	    	//String password = "123456";
	    	 
	        MessageDigest md = MessageDigest.getInstance("MD5");
	        md.update(password.getBytes());
	 
	        byte byteData[] = md.digest();
	 
	        //convert the byte to hex format method 1
	        StringBuffer sb = new StringBuffer();
	        for (int i = 0; i < byteData.length; i++) 
	        {
	         sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
	        }
			
			
			String consulta =login+"\n"+sb.toString()+"\n"+"01"+"\n"+"0000";
			Socket servidorConsultas = new Socket("127.0.0.1", 15800);
			PrintWriter consultaServidorConsultas = new PrintWriter(servidorConsultas.getOutputStream(), true);
			consultaServidorConsultas.println(consulta);
			BufferedReader resultadoConsulta  = new BufferedReader(new InputStreamReader(servidorConsultas.getInputStream())); 
			String resultado = ""; 
			ArrayList<String> lineasLeidas = new ArrayList<String>();
			
			while (resultado != null)
			{
				resultado = resultadoConsulta.readLine();
				if(resultado != null)
				{
					lineasLeidas.add(resultado);
				}				
			}			
			System.out.println(String.format("Respueta %1$tH:%1$tM:%1$tS:%1$tL", java.util.Calendar.getInstance()));
			System.out.println("Total lineas: "+(lineasLeidas.size()-1));
			if(lineasLeidas.size() > 0)
			{
				for(String s: lineasLeidas)
				{
					System.out.println(s);
				}
			}
			else
			{
				System.out.println("La consulta no arrojo resultados");
			}
			consultaServidorConsultas.close();
			resultadoConsulta.close();
			servidorConsultas.close();
			
		} 
		catch (UnknownHostException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		} 
		catch (IOException e) 
		{
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

}
